package com.xiaochangwei.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.mysql.jdbc.StringUtils;
import com.xiaochangwei.web.beans.User;
import com.xiaochangwei.web.beans.UserInfo;
import com.xiaochangwei.web.service.UserService;
import com.xiaochangwei.web.utils.Constant;
import com.xiaochangwei.web.utils.Encryptor;

/**
 * @since 2017年3月9日 下午2:29:38
 * @author 肖昌伟 317409898@qq.com
 * @description
 */
@Controller
public class LoginRegisterController extends BaseController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "doLogin", method = { RequestMethod.POST })
	public ModelAndView doLogin(User user, ModelAndView mv, HttpSession session, HttpServletRequest request) {
		if (!StringUtils.isNullOrEmpty(user.getUsername()) && !StringUtils.isNullOrEmpty(user.getPassword())) {
			User dbUser = userService.getUserByName(user.getUsername());
			if (dbUser != null) {
				if (dbUser.getStatus() != 1) {
					mv.addObject("msg", "账号异常或已被锁定");
				} else {
					if (Encryptor.pswdIsCorrect(user.getPassword(), dbUser.getPassword(), dbUser.getSalt())) {
						dbUser.setLoginCount(dbUser.getLoginCount() + 1);
						userService.updateLoginCount(dbUser);
						session.setAttribute(Constant.SESSION, dbUser);
						return new ModelAndView(new RedirectView(request.getContextPath() + "/user/userDetail.html"));
					} else {
						mv.addObject("msg", "用户名或密码不正确");
					}
				}
			}
		} else {
			mv.addObject("msg", "输入信息不完整");
		}
		mv.setViewName("login");
		return mv;
	}

	@RequestMapping(value = "doRegister", method = { RequestMethod.POST })
	public ModelAndView doRegister(User user, ModelAndView mv, HttpSession session) {
		if (!StringUtils.isNullOrEmpty(user.getUsername()) && !StringUtils.isNullOrEmpty(user.getPassword())
				&& !StringUtils.isNullOrEmpty(user.getRepassword())) {
			if (user.getPassword().equals(user.getRepassword())) {
				if (userService.getUserByName(user.getUsername()) != null) {
					mv.addObject("msg", "用户名已存在，请更换其它用户名");
				} else {
					user.setSalt(Encryptor.generateSalt());
					user.setPassword(Encryptor.generateEncodePasword(user.getSalt(), user.getPassword()));
					userService.insertUser(user);
					//同时增加用户详情数据
					UserInfo userInfo = new UserInfo();
					userInfo.setId(user.getId());
					userService.insertUserInfo(userInfo);
					
					return new ModelAndView(new RedirectView("login.html"));
				}
			} else {
				mv.addObject("msg", "两次输入密码不一致");
			}
		} else {
			mv.addObject("msg", "输入信息不完整");
		}
		mv.setViewName("register");
		return mv;
	}
}
